package net.xmmpp.uc.im.bootstrap.web.controller;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import net.xmmpp.uc.im.bootstrap.web.config.Node;
import net.xmmpp.uc.im.bootstrap.web.config.NodesProperties;
import net.xmmpp.uc.im.common.dto.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;


@RestController
@RequestMapping("broker")
public class PortalController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PortalController.class);

    @Autowired
    private NodesProperties nodesConfig;

    private static HashFunction hashFunction = Hashing.murmur3_128();

    @GetMapping("{userId}")
    public Response<Node> getUser(@PathVariable("userId") String userId) {

        HashCode hashCode = hashFunction.hashString(userId, StandardCharsets.UTF_8);
        int index = Math.abs(hashCode.hashCode()) % nodesConfig.getNodes().size();
        Response<Node> responseEntity = new Response<>(nodesConfig.getNodes().get(index));

        return responseEntity;
    }

}
